<template>
	<view class="content">
		<!-- <web-view :webview-styles="webviewStyles" @message="handleMessage"></web-view> -->
		<map id="map" class="map" :show-location="true" :markers="markers" 
		:latitude="selfgcjLocation.latitude" :longitude="selfgcjLocation.longitude"></map>
		<view class="body">
			<div>
				<div class="item-row" style="align-items: center;">
					<label>地点</label>
					<p style="padding-left: 10px;">{{form.address}}</p>
				</div>
				<div class="item-row" style="align-items: center;">
					<label>留言</label>
					<uni-easyinput v-model="form.remark" placeholder="请输入留言" :inputBorder="false"/>
				</div>
				<div class="item-row">
					<label>附件</label>
					<uni-file-picker style="padding-left: 10px;" @select="fileSelect" @delete="fileDelete" :auto-upload="false" 
						title="最多选择3张图片" limit="3" fileMediatype="image" />
				</div>
			</div>
			<form>
				<view class="uni-btn-v" style="display: flex;padding:20px;">
					<button type="primary" :disabled="sbSignFlag" @click="formSubmitBefore('sbqd')">上班签到</button>
					<button type="primary" :disabled="xbSignFlag" @click="formSubmitBefore('xbqd')">下班签到</button>
				</view>
			</form>
		</view>
	</view>
</template>

<script>
	import {
		setToken,getToken
	} from '@/utils/auth'
	import {GPS} from '@/utils/GPS'
	import { queryGeocoder } from '@/api/mapGis/mapGis'
	import  configs from '@/config'
	import {uuid} from "@/plugins/package/utils";
	import { addCheckInWork, updateCheckInWork, queryCheckInWorkByParam } from '@/api/dums/am/time'
	export default {
		data() {
			return {
				sbSignFlag: true,
				xbSignFlag: true,
				roles: this.$store.state.user.roles,
				form:{
					timetableId:"",
					address:"定位中...",
					remark:null,
					userName:this.$store.state.user.userInfo.nickName,
					userId:this.$store.state.user.userInfo.id,
					logInNum:this.$store.state.user.userInfo.userName,
					tcDate: null,
					userType: null,//1:采集员，2：环卫，3：执法
				},
				params: {},
				webviewStyles: {
					height:"300",
					progress: {
						color: "#FF3333"
					}
				},
				filePaths:[],
				imagesList:[],
				selfLocation: {
					latitude: '',
					longitude: ''
				},
				selfgcjLocation: {
					latitude: '',
					longitude: ''
				},
				checkInWork:{},
				mapContext:null,
				markers:[]
			}
		},
		components:{
		},
		onReady() {
			//地图初始化
			this.mapContext = uni.createMapContext("map", this);
			
			// 仅调用初始化，才会触发 on.("markerClusterCreate", (e) => {})
			this.mapContext.initMarkerCluster({
				enableDefaultStyle: false,
				zoomOnClick: true,
				gridSize: 60,
				complete(res) {
				  console.log('initMarkerCluster', res)
				}
			});
		
			this.mapContext.on("markerClusterCreate", (e) => {
				console.log("markerClusterCreate", e);
			});
			  
			// this.addMarkers();
		},
		onLoad(){
			console.log(GPS.gcj_encrypt)
			let _this = this;
			uni.getLocation({
				type: 'wgs84',
				success: function (res) {
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
					console.log(typeof res.latitude);
					_this.selfLocation.latitude = res.latitude;
					_this.selfLocation.longitude = res.longitude;
					let pos = GPS.gcj_encrypt(res.latitude, res.longitude);
					_this.selfgcjLocation.latitude = pos.lat;
					_this.selfgcjLocation.longitude = pos.lon;
					_this.markers = [{
						latitude: pos.lat,
						longitude: pos.lon,
						id: 1,
						// iconPath: "https://bpic.51yuansu.com/pic3/cover/01/06/40/590138a6b61a9_610.jpg",
						iconPath: "/static/images/common/location_fill.png",
					    joinCluster: true, // 指定了该参数才会参与聚合
					    width: 300,
					    height: 300 
					}];
					_this.queryGeocoder();
				}
			});
			// 正式版 地址 http://10.8.88.26:6061/#/  http://localhost:3000/#/
			// let url = 'http://10.8.88.26:6062/#/'
			let url = 'http://10.8.89.208:9091/#/'
			let aurl = "/pages/waterSupply/DailyManagement/map/map";
			let token = getToken()
			// 正式版 地址 http://10.8.88.26:6061/#/
			//this.params.url = url + event.aurl + '?token=' + event.token
			setTimeout(()=>{
				// this.params.url = url + decodeURI(aurl) + '?token=' + token
				// console.log(this.params.url);
			},2000)
			console.log(JSON.stringify(this.roles));
			if(this.roles.includes("cjy")){
				this.form.remark1 = "1"; //采集员
			}else if(this.roles.includes("assess_person")){
				this.form.remark1 = "2"; //环卫
			}else if(this.roles.includes("zfkq")){
				this.form.remark1 = "3"; //执法考勤人员
			}else if(this.roles.includes("xgkqry")){
				this.form.remark1 = "4"; //协管考勤人员
			}
			//判断是否分配打卡角色
			if(!this.form.remark1){
				this.$modal.msgError("未分配打卡岗位")
				return;
			}
			let param = {
				userId: this.$store.state.user.userInfo.id,
				userType: this.form.remark1, //1:采集员，2：环卫，3：执法
			};
			if(param.userType==4)param.userType=3;
			console.log(JSON.stringify(param));
			queryCheckInWorkByParam(param).then(res=>{
				console.log(JSON.stringify(res))
				if(res.data){
					this.checkInWork = res.data;
					if(res.data.checkInData){
						this.form.timetableId = res.data.checkInData.timetableId;
						this.form.tcDate = new Date(res.data.checkInData.workDate).getTime();
						this.form.id = res.data.checkInData.id;
						if(!res.data.checkInData.tcOnWorkTime){
							this.sbSignFlag=false;
						}
						if(!res.data.checkInData.tcOffWorkTime){
							this.xbSignFlag=false;
						}
					}
				}
			});
		},
		methods: {
			addMarkers() {
				const positions = [
				  {
					latitude: 23.099994,
					longitude: 113.324520,
				  }, {
					latitude: 23.099994,
					longitude: 113.322520,
				  }, {
					latitude: 23.099994,
					longitude: 113.326520,
				  }, {
					latitude: 23.096994,
					longitude: 113.329520,
				  }
				]
		
				const markers = []
		
				positions.forEach((p, i) => {
				  console.log(i)
				  markers.push(
					Object.assign({},{
					  id: i + 1,
					  iconPath: "/static/images/common/location_fill.svg",
					  width: 150,
					  height: 150,
					  joinCluster: true, // 指定了该参数才会参与聚合
					},p)
				  )
				})
				console.log(JSON.stringify(markers))
				this.markers = markers;
			},
			fileSelect(e){console.log(e);
				for (let i = 0; i < e.tempFiles.length; i++) {
					this.filePaths.push({"uri":e.tempFilePaths[i]});
				}
			},
			fileDelete(e){console.log(e);
				for (let i = 0; i < this.filePaths.length; i++) {
					if (this.filePaths[i].uri == e.tempFilePath) {
						this.filePaths.splice(i, 1);
					}
				}
			},
			fileUpload(){
				return new Promise((resolve,reject) => {
					uni.uploadFile({
						url: configs.baseUrl+'/am/amAttach/uploadFiles', //仅为示例，非真实的接口地址
						files: this.filePaths,
						name: 'files',
						header:{
							"Authorization": "Bearer " + getToken() 
						},
						formData: {
							
						},
						success: (res) => {
							if(res.statusCode==200){
								var data = JSON.parse(res.data);
								this.imagesList = data.data;
								resolve(data.data);
							}else{
								uni.showToast({
									duration: 3000,
									icon: "error",
									title:res.msg
								});
							}
						},
						fail() {
							reject()
						}
					});
				})
			},
			formSubmitBefore(type){
				console.log(type)
				if(type == "sbqd"){
					this.form.onPositionX = this.selfLocation.latitude;
					this.form.onPositionY = this.selfLocation.longitude;
					this.form.onWorkAddress = this.form.address;
					this.form.tcOnWorkTime = new Date(this.checkInWork.nowTime).getTime();
					//判断是否迟到
					if(this.checkInWork.checkInData.beginTime<this.checkInWork.nowTime.split(" ")[1]){
						this.form.isLate = 1;
					}else{
						this.form.isLate = 0;
					}
				}else{
					this.form.offPositionX = this.selfLocation.latitude;
					this.form.offPositionY = this.selfLocation.longitude;
					this.form.offWorkAddress = this.form.address;
					this.form.tcOffWorkTime = new Date(this.checkInWork.nowTime).getTime();
					//判断是否早退
					if(this.checkInWork.checkInData.endTIme>this.checkInWork.nowTime.split(" ")[1]){
						this.form.isEarly = 1;
					}else{
						this.form.isEarly = 0;
					}
				}
				if(this.filePaths.length>0){
					this.fileUpload().then(res=>{
						let fileIds = "";
						//拼接fileId
						res.map(f=>{
							fileIds += f.fileid+",";
						});
						if(type == "sbqd"){
							this.form.tdSImgPath = fileIds;
						}else{
							this.form.tdEImgPath = fileIds;
						}
						this.formSubmit(type);
					});
				}else{
					this.formSubmit(type);
				}
			},
			formSubmit(type){
				if(type == "sbqd"){
					addCheckInWork(this.form).then(res=>{
						console.log(res)
						if(res.code == "200"){
							uni.showToast({
								duration: 3000,
								icon: "success",
								title:res.msg
							});
							setTimeout(()=>{
								uni.navigateBack(0)
							}, 500);
							
						}else{
							uni.showToast({
								duration: 3000,
								icon: "error",
								title:res.msg
							});
						}
					});
				}else{
					updateCheckInWork(this.form).then(res=>{
						console.log(res)
						if(res.code == "200"){
							uni.showToast({
								duration: 3000,
								icon: "success",
								title:res.msg
							});
							setTimeout(()=>{
								uni.navigateBack(0)
							}, 500);
						}else{
							uni.showToast({
								duration: 3000,
								icon: "error",
								title:res.msg
							});
						}
					});
				}
			},
			handleMessage(evt) {
				const eventChannel = this.getOpenerEventChannel();
				console.log(JSON.stringify(evt));
				console.log('接收Html发送过来的消息：' + JSON.stringify(evt.detail.data[0]));
				let coordinate = evt.detail.data[0];
				coordinate.ver = "1";
				let params = {
					"postStr":JSON.stringify(coordinate),
					"type":"geocode"
				}
				queryGeocoder(params).then(res => {
					if(res.result){
						coordinate.address = res.result.formatted_address
					}
					eventChannel.emit('acceptDataFromOpenedPage', {coordinate: coordinate});
				})
				
			},
			queryGeocoder(point){
				let coordinate = {
					lon: this.selfLocation.longitude,
					lat: this.selfLocation.latitude
				};
				coordinate.ver = "1";
				let params = {
					"postStr":JSON.stringify(coordinate),
					"type":"geocode"
				}
				queryGeocoder(params).then(res => {
					console.log(JSON.stringify(res));
					if(res.result){
						this.form.address = res.result.formatted_address
					}
				}).catch(err=>{
					console.log(err)
					this.form.address = err
				})
			}
		}
	}
</script>

<style>
	.item-row{
		display: flex;
		padding: 10px 40px;
	}
	.item-row label{
		font-family: 思源黑体;
		font-size: 16px;
		font-weight: normal;
		line-height: 16px;
		letter-spacing: 0em;
		color: #000000;
		width: 50px;
	}
	.map{
		height:200px;
		width:100%;
	}
</style>